<?php
namespace app\cash\controller;
use think\Controller;
use think\Db;
use app\cash\model\OrderDetails;
use app\cash\model\StoreGoodsLog;

class Pay extends Controller{
    /**
     * @Author lignyun
     * @Desc    检查登录
     * 2018-04-09
     */
    public function _initialize(){
        if (!session('cash_user')) {
            $this->redirect('@cash/login/index');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    下单支付
     * array(9) {
    ["mobile"] => string(11) "18765227746"
    ["yue"] => string(7) "1000.00"
    ["coupon_id"] => string(1) "5"
    ["qrcode"] => string(0) ""
    ["goods_id"] => array(4) {
    [0] => string(3) "134"
    [1] => string(2) "90"
    [2] => string(3) "114"
    [3] => string(3) "136"
    }
    ["goods_spec_id"] => array(4) {
    [0] => string(4) "1226"
    [1] => string(2) "89"
    [2] => string(3) "113"
    [3] => string(4) "1228"
    }
    ["goods_num"] => array(4) {
    [0] => string(1) "1"
    [1] => string(1) "1"
    [2] => string(1) "1"
    [3] => string(1) "4"
    }
    ["goods_discount"] => array(4) {
    [0] => string(1) "0"
    [1] => string(1) "0"
    [2] => string(1) "0"
    [3] => string(3) "9.0"
    }
    ["pay_type"] => string(1) "1"
    }
     * 2018-06-08
     */
    public function index(){
        $post = input('post.');
        $store_id = session('cash_user')['store_id'];
        $store = $this->get_store($store_id);
        $member = $this->get_member($post['mobile'],$post['uid']);

        if(empty($post['mobile']) && !empty($post['yue'])){
            $this->error('请查询会员信息，再使用余额付款','');
        }
        $this->create_goods($post,$store_id,$member,$store);
    }

    /**
     * @Author  lingyun
     * @Desc    生成订单记录
     *          ys_order
     *          ys_order_details
     *          ys_order_action
     *          ys_pay_log
     *          ys_user
     *          ys_user_wallet_log
     *          ys_user_point_log
     *          ys_store
     *          ys_store_credit_log
     *          ys_store_goods_stock
     *          ys_store_goods_log
     */
    private function create_goods($post,$store_id,$member,$store){
        $goods_id = $post['goods_id'];
        $goods_spec_id = $post['goods_spec_id'];
        $goods_num = $post['goods_num'];
        $goods_discount = $post['goods_discount'];
        $s_goods_amount = $post['s_goods_amount'];          //商品改价
        $sn = 'L' . build_order_no();           //订单号
        $uid = empty($member)?0:$member['uid'];
        $mobile = empty($member)?'':$member['mobile'];

        $order_goods_details = [];          //订单详情
        $final_amount = 0;                  //最终支付价
        $discount_amount = 0;                  //折扣价
        $all_num = array_sum($goods_num);       //所有的商品数量
        $store_goods_stock_arr = [];            //商品库存日志记录

        $coupon_info = $this->get_coupon($post['coupon_id'],$all_num);
        $coupon = $coupon_info['coupon'];               //优惠券信息
        $coupon_signal_price = $coupon_info['coupon_signal_price'];     //平摊优惠券价格
        $chengben = 0;              //商品成本价
        $chengben_price = 0;        //商品销售成本价


        $receipt = '';          //线下小票信息
//        $receipt .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号：'.$sn.'</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员：' . session("cash_user")["realname"] . '</td></tr><tr><td colspan="4" style="text-align: center">—————————————————————</td></tr><tr><td style="width: 10mm;">商品</td><td>数量</td><td>单价</td><td>金额</td><td>折扣</td></tr>';

        $receipt .= '<tr><td colspan="4" style="font-size: large;text-align: center">'.$store["title"].'</td></tr><tr><td colspan="4" style="font-size: large;text-align: center">&nbsp;</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">单号：'.$sn.'</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller">收银员：' . session("cash_user")["realname"] . '</td></tr><tr><td colspan="4" style="text-align: left">—————————————————</td></tr><tr><td>商品</td><td>数量</td><td>单价</td><td>金额|折扣</td></tr>';

        foreach($goods_id as $k => $v){
            $map['a.goods_id'] = ['eq',$v];
            $map['a.goods_spec_id'] = ['eq',$goods_spec_id[$k]];
            $map['a.store_id'] = ['eq',$store_id];

            $goods_result = $this->get_goods($map,$store,$goods_num[$k],$member,$goods_discount[$k],$s_goods_amount[$k]);       //获取商品信息

            $goods_discount[$k] = $goods_result['goods_discount'];                  //商品折扣
            $discount_signal_price= $goods_result['discount_signal_price'];         //商品折扣单价
            $goods = $goods_result['goods'];                                        //商品详情信息

            $chengben = $chengben+$goods['chengben'];                               //成本
            $chengben_price = $chengben_price+$goods['chengben_price'];                   //销售成本

            $arr = $this->create_order_detail($uid,$store_id,$goods,$goods_num[$k],$goods_discount[$k],$coupon_signal_price,$discount_signal_price);                            //创建订单详情记录

            array_push($order_goods_details,$arr);      //订单详情记录

            $store_goods_stock_arr[$k] =$this->create_goods_stock_log($store_id,$goods,$goods_num[$k],$sn);     //商品库存记录

            $final_amount = $final_amount + $goods['final_amount']*$goods_num[$k] ;             //订单总价
            $discount_amount =  $discount_amount + $discount_signal_price*$goods_num[$k];       //折扣总金额

            $receipt .='<tr style="font-size: smaller;width: 25mm;"><td colspan="4" style="text-align: left">' . $goods["name"].' '.$goods["title"]. '</td></tr>';
            $receipt .= '<tr style="font-size: smaller;"><td style="width: 25mm"></td><td>' . $goods_num[$k] . '</td><td>' . $goods["final_amount"] . '</td><td>' . $goods["final_amount"]*$goods_num[$k].'|'.$goods_discount[$k] . '</td></tr>';

        }

        $ffinal_amount = $final_amount-$discount_amount-$coupon['reduce'];              //最终支付金额

        $receipt .= '<tr><td colspan="4" style="text-align: center">—————————————————</td></tr>';

        $receipt .= '<tr><td colspan="2" style="text-align: left;font-size: smaller">总计：' . $final_amount.'</td><td colspan="2" style=";text-align: center;font-size: smaller;">折扣：'.$discount_amount.'</td></tr>';

        $receipt .= '<tr><td colspan="2" style="text-align: left;font-size: smaller;">实付：' . $ffinal_amount.'</td><td colspan="2" style="text-align: left;font-size: smaller">优惠券：' . $coupon["reduce"].'</td></tr>';

        if(empty($post['yue'])){           //判断付款方式，余额够用则只有余额付款，其它表示组合付款
            $pay_type = $post['pay_type'];
            if(empty($pay_type)){
                $this->error('请选择付款方式','');
            }else if($pay_type == 4){           //现金支付
                if($post['cash'] < $ffinal_amount){
                    $this->error('现金不足，不能支付','');
                }
            }
            $pay_type_two = 0;
            if($pay_type == 4 || $pay_type == 5 || $pay_type == 6 || $pay_type == 7){       //现金、银行卡、美团、饿了么
                $pay_status = 1;
                $order_status = 4;
                $remark = '订单已完成';
            }else{
                $pay_status = 0;
                $pay_type_two = 0;
                $order_status = 0;
                $remark = '订单待支付';
            }
        }else if($post['yue'] > $ffinal_amount){      //余额付款
            $pay_type = 3;      //余额付款
            $pay_type_two = 0;
            $pay_status = 1;
            $order_status = 4;
            $remark = '订单已完成';
        }else{          //组合付款
            $pay_type = $post['pay_type'];
            if(empty($pay_type)){
                $this->error('请选择支付方式','');
            }else if($pay_type == 4){           //现金支付
                if($post['cash'] < $ffinal_amount-$post['yue']){
                    $this->error('现金不足，不能支付','');
                }
            }
            $pay_type_two = $post['yue'];           //组合付款使用余额
            if($pay_type == 4 || $pay_type == 5 || $pay_type == 6 || $pay_type == 7){
                $pay_status = 1;
                $order_status = 4;
                $remark = '订单已完成';
            }else{
                $pay_status = 0;
                $order_status = 0;
                $remark = '订单待支付';
            }
        }

        if($store['is_jiameng'] == 1){              //加盟店
            $remark = '订单已完成';
            $pay_status = 1;
            $order_status = 4;
        }
        if($pay_status == 1){
            $pay_time = time();
        }else{
            $pay_time = 0;
        }


        if($pay_type_two == 0){
            $use_yue = '';
            $pty = $ffinal_amount-$pay_type_two;
        }else{
            $use_yue = '|会员卡：('.$pay_type_two.')';
            $pty = $ffinal_amount-$pay_type_two;
        }

        if($pay_type == 1){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：支付宝（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 2){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：微信（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 3){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：会员卡（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 4){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：现金（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 5){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：银行卡（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 6){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：美团（'.$pty.'）'.$use_yue.'</td></tr>';
        }else if($pay_type == 7){
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">支付方式：饿了么（'.$pty.'）'.$use_yue.'</td></tr>';
        }

        if(!empty($member)){            //显示会员信息
            if($post['yue'] <= $final_amount-$coupon['reduce']-$discount_amount){         //余额付款
                $user_money = $member['user_money'] - $post['yue'];
            }else{
                $user_money = $member['user_money'] - $final_amount+$coupon['reduce']+$discount_amount;
            }

            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">姓名：' . $member["realname"] . '     手机：' . $member["mobile"] . '</td></tr><tr><td colspan="4" style=";text-align: center">&nbsp;</td></tr>';
            $receipt .='<tr><td colspan="4" style="text-align: left;font-size: smaller">会员卡：' . $member["pay_code"] . '     余额：￥' . $user_money . '</td></tr><tr><td colspan="4" style=";text-align: left">&nbsp;</td></tr>';
        }

        //新增数据 -- 2018-08-31  start
        if(session('cash_user.store_id') == 14) {
            $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">首次购物五折优惠</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">凭小票可享以下优惠</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/07-9/30 三⻆角形蛋糕全场半价</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/07-9/09 全场苏打水,⽔果茶,奶茶饮品1折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/10-9/16 全场苏打水,⽔果茶,奶茶饮品3折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/17-9/23 全场苏打水,水果茶,奶茶饮品5折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">9/24-9/30 全场苏打水,水果茶,奶茶饮品7折</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">限时充值活动</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;"></td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值100 送 20</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值200 送 80</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值500 送 200</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值1000 送 600</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">充值就送神秘卡券大礼包</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">—————————————————</td></tr><tr><td colspan="4" style="text-align: left;font-size: smaller;">本次活动最终解释权归一朵餐饮有限公司所有</td></tr>';
        }
        //新增数据结束 -- 2018-08-31  end

        $receipt .= '<tr><td colspan="4" style="text-align: left;font-size: smaller;">' . $store["address"] . '</td></tr>';
        $receipt .= '<tr><td colspan="4" style="text-align: left">' . date('Y-m-d H:i:s') . '</td></tr>';
        $receipt .= '<tr><td colspan="4" style="text-align: left">' . '欢迎您再次光临' . '</td></tr>';


        //订单信息
        $order_arr = [
            'uid'=>$uid,
            'coupon_id'=>$post['coupon_id'],
            'coupon_price'=>$coupon['reduce'],
            'order_type'=>0,
            'order_sn'=>$sn,
            'order_status'=>$order_status,
            'store_id'=>$store_id,  //门店id
            'mobile'=>$mobile,
            'pay_type'=>$pay_type,
            'pay_time'=>$pay_time,
            'pay_type_two'=>$pay_type_two,          //余额支付部分
            'pay_status'=>$pay_status,
            'goods_num'=>$all_num,
            'goods_price'=>$final_amount,
            'order_amount'=>$ffinal_amount,
            'receipt'=>$receipt,
            'final_amount'=>$ffinal_amount,
            'discount_amount'=>$discount_amount,
            'addtime'=>time(),
            'cashier'=>session('cash_user')['id'],
            'chengben'=>$chengben,
            'chengben_price'=>$chengben_price,
            'is_yuding'=>$post['is_yuding'],
        ];

        $order_id = db('order')->insertGetId($order_arr);

        foreach ($order_goods_details as $k => $v) {
            if($v['discount_num'] == '无'){
                $order_goods_details[$k]['discount_num'] = 0;
            }
            $order_goods_details[$k]['status'] = $order_status;
            $order_goods_details[$k]['order_id'] = $order_id;
        }

        $orderdetailsmodel = new OrderDetails();
        $orderdetailsmodel->insertAll($order_goods_details);            //插入订单详情记录
        $order_action_pay_status = empty($pay_status)?0:1;
        $order_action = [
            'uid' => $uid,
            'order_id' => $order_id,
            'action_user' => 0,
            'order_status' => $order_status,
            'pay_status' => $order_action_pay_status,
            'status_desc' => $remark,
            'storeid' => $store_id,
            'addtime' => time(),
        ];

        db('order_action')->insert($order_action);                      //订单动作记录

        if ($pay_type == 1) {
            $fild = 'al_money';
        } else if ($pay_type == 2) {
            $fild = 'wx_money';
        } else if ($pay_type == 3) {          //余额
            $fild = 'user_money';
        } else if ($pay_type == 4) {
            $fild = 'xianjin_money';
        } else if ($pay_type == 5) {
            $fild = 'bank_money';
        } else if ($pay_type == 6) {
            $fild = 'meituan_money';
        } else if ($pay_type == 7) {
            $fild = 'elema_money';
        }


        if ($pay_status == 1) {               //加盟店或者订单支付完成
            if ($pay_type_two == 0) {         //全款支付
                $pay_log_arr = [
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'order_type' => 2,
                    'uid' => $uid,
                    'store_id' => $store_id,          //门店id
                    'pay_type' => $pay_type,
                    'pay_sign' => 1,
                    'amount' => $ffinal_amount,
                    'remark' => '线下购买商品，订单号' . $sn . '，总价：' . $ffinal_amount,
                    'addtime' => time()
                ];
                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                //更新商品库存
                foreach ($store_goods_stock_arr as $k => $v) {
                    db('store_goods_stock')->where(['goods_id' => $v['goods_id'], 'goods_spec_id' => $v['goods_spec_id'], 'store_id' => $v['store_id'], 'is_deleted' => 0])->setDec('stock', $v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志


                $store_credit_log = [
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'type' => 1,
                    'credit' => $ffinal_amount,
                    'cur_credit' => $store['total_amount'] + $ffinal_amount,
                    'remark' => '销售商品收入',
                    'addtime' => time(),
                    'order_type' => 1,
                    'order_sn' => $sn,
                    'pay_type' => $pay_type
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $store['total_amount'] + $ffinal_amount;
                $store_credit_arr[$fild] = $store[$fild] + $ffinal_amount;
                if ($pay_type == 3) {             //余额全款支付
                    $store_credit_arr['credit'] = $store['credit'] + $ffinal_amount;      //更新门店转账余额
                }
                db('store')->where('id', $store_id)->update($store_credit_arr);

                if ($pay_type == 3) {         //使用余额支付
                    $data_wallet_arr = [
                        'uid' => $uid,
                        'admin_id' => 0,
                        'store_id' => $store_id,
                        'order_id' => $order_id,
                        'order_sn' => $sn,
                        'pay_time' => time(),
                        'pay_status' => 1,
                        'pay_type' => 3,
                        'amount' => $ffinal_amount,
                        'cur_amount' => $member['user_money'] - $ffinal_amount,
                        'sign' => 2,
                        'chargetype' => 1,
                        'charge_cn' => '支付订单',
                        'addtime' => time()
                    ];
                    //记录余额记录
                    db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                    db('user')->where('uid', $uid)->setDec('user_money', $ffinal_amount);
                }
            } else {
                $log_money = $final_amount - $discount_amount - $coupon['reduce'] - $pay_type_two;
                $pay_log_arr1 = [
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'order_type' => 2,
                    'uid' => $uid,
                    'store_id' => $store_id,          //门店id
                    'pay_type' => $pay_type,
                    'pay_sign' => 1,
                    'amount' => $log_money,
                    'remark' => '线下购买商品，订单号' . $sn . '，总价：' . $log_money,
                    'addtime' => time()
                ];
                $pay_log_arr2 = [
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'order_type' => 2,
                    'uid' => $uid,
                    'store_id' => $store_id,          //门店id
                    'pay_type' => 3,
                    'pay_sign' => 1,
                    'amount' => $pay_type_two,
                    'remark' => '线下购买商品，订单号' . $sn . '，总价：' . $pay_type_two,
                    'addtime' => time()
                ];
                db('pay_log')->insert($pay_log_arr1);            //新增支付记录
                db('pay_log')->insert($pay_log_arr2);            //新增支付记录

                $data_wallet_arr = [
                    'uid' => $uid,
                    'admin_id' => 0,
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'order_sn' => $sn,
                    'pay_time' => time(),
                    'pay_status' => 1,
                    'pay_type' => 3,
                    'amount' => $pay_type_two,
                    'cur_amount' => $member['user_money'] - $pay_type_two,
                    'sign' => 2,
                    'chargetype' => 1,
                    'charge_cn' => '支付订单',
                    'addtime' => time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                db('user')->where('uid', $uid)->setDec('user_money', $pay_type_two);

//                db('store')->where('id',$store_id)->setInc('user_money',$pay_type_two);     //更新门店会员卡金额数量
                //更新商品库存
                foreach ($store_goods_stock_arr as $k => $v) {
                    db('store_goods_stock')->where(['goods_id' => $v['goods_id'], 'goods_spec_id' => $v['goods_spec_id'], 'store_id' => $v['store_id'], 'is_deleted' => 0])->setDec('stock', $v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志

                $store_credit_log = [
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'type' => 1,
                    'credit' => $log_money,
                    'cur_credit' => $store['total_amount'] + $log_money,
                    'remark' => '销售商品收入',
                    'addtime' => time(),
                    'order_type' => 1,
                    'order_sn' => $sn,
                    'pay_type' => $pay_log_arr1['pay_type']
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money;
                $store_credit_arr[$fild] = $store[$fild] + $log_money;
                db('store')->where('id', $store_id)->update($store_credit_arr);

                $store_credit_log = [
                    'store_id' => $store_id,
                    'order_id' => $order_id,
                    'type' => 1,
                    'credit' => $pay_type_two,
                    'cur_credit' => $store['total_amount'] + $log_money + $pay_type_two,
                    'remark' => '销售商品收入',
                    'addtime' => time(),
                    'order_type' => 1,
                    'order_sn' => $sn,
                    'pay_type' => 3
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $store['total_amount'] + $log_money + $pay_type_two;
                $store_credit_arr['credit'] = $store['credit'] + $pay_type_two;
                $store_credit_arr['user_money'] = $store['user_money'] + $pay_type_two;
                db('store')->where('id', $store_id)->update($store_credit_arr);
            }

            if($coupon['id'] != 0){
                db('user_ycard')->where(['coupon_id'=>$coupon['id'],'uid'=>$uid])->update(['order_id'=>$order_id,'used_time'=>time(),'is_used'=>1]);
            }

            if(!empty($uid)){
                //变更积分
                shouyintai_point($uid,$ffinal_amount,$store_id,$order_id,$money=0,$sn,1);
            }
            $this->success('支付成功，即将开启打印页面','',$receipt);
        }else if($pay_type == 1){           //支付宝支付
            if($post['qrcode'] == ''){
                $this->error('请先扫描支付码','');
            }
            $pay_result = $this->redirect(url('Alipay/pay').'?order_id='.$order_id."&auth_code=".$post['qrcode']);
        }else if($pay_type == 2){          //微信支付
            if($post['qrcode'] == ''){
                $this->error('请先扫描支付码','');
            }
            $pay_result = $this->redirect(url('Wxpay/pay').'?order_id='.$order_id."&auth_code=".$post['qrcode']);
        }

    }

    /**
     * @Author  lingyun
     * @Desc    获取商品信息
     * 2018-06-09
     */
    private function get_goods($map,$store,$goods_num,$member,$goods_discount,$goods_final_amount){
        $goods = db('store_goods_stock')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where($map)->field('a.id,a.goods_id,a.goods_spec_id,a.stock,is_diannei,a.trim_price,b.name,b.member_level_id,a.is_deleted,a.onsale,c.title,c.price,c.member_price,c.peifang_ids,a.chengben,a.chengben_price')->find();

        $chengben_result = $this->get_chengben($goods['peifang_ids'],$goods['chengben'],$goods['chengben_price']);
        $goods['chengben'] = $goods_num*$chengben_result['chengben'];
        $goods['chengben_price'] = $goods_num*$chengben_result['chengben_price'];

        if($goods['onsale'] == 0 || $goods['is_deleted'] ==1){
            $this->error($goods['name'].$goods['title'].'已下架，请重新选择商品','');
        }else if($goods['stock'] < $goods_num){
            $this->error($goods['name'].$goods['title'].'库存不足，请重新选择商品','');
        }

//        if($store['price_status'] == 1 && $goods['trim_price'] !=0){
//            $goods['final_amount'] = $goods['trim_price'];
//        }else if(!empty($member)){
//            if($member['level_id'] >= $goods['member_level_id']){
//                $goods['final_amount'] = $goods['member_price'];
//            }
//        }else{
//            $goods['final_amount'] = $goods['price'];
//        }
        $goods['final_amount'] = $goods_final_amount;

        if($goods_discount != 0){      //折扣
            $discount_signal_price = $goods['final_amount']*(10-$goods_discount)/10;
            $goods_discount = $goods_discount;

        }else{
            $goods_discount = '无';
            $discount_signal_price = 0;
        }

        return ['goods'=>$goods,'discount_signal_price'=>$discount_signal_price,'goods_discount'=>$goods_discount];
    }

    /**
     * @Author  lingyun
     * @Desc    计算成本
     * 2018-06-09
     */
    private function get_chengben($peifang_ids,$chengben,$chengben_price){
        if(empty($chengben) || empty($chengben_price)){         //没有成本价
            if(empty($peifang_ids)){
                $chengben = 0;
                $chegnben_price = 0;
            }
            $peifang = db('goods_peifang')->where('id','in',$peifang_ids)->field('chengben,chengben_price')->select();

            $chengben = array_sum(array_map(function($peifang){return $peifang['chengben'];}, $peifang));
            $chengben_price = array_sum(array_map(function($peifang){return $peifang['chengben_price'];}, $peifang));
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }else{
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }
    }

    /**
     * @Author  lingyun
     * @Desc    创建订单详情记录
     */
    private function create_order_detail($uid,$store_id,$goods,$goods_num,$discount_num,$coupon_signal_price,$discount_signal_price){
        $arr['uid'] = $uid;
        $arr['spec_id'] = $goods['goods_spec_id'];
        $arr['spec_detail'] = $goods['title'];
        $arr['goods_id'] = $goods['goods_id'];
        $arr['goods_num'] = $goods_num;
        $arr['spec_price'] = $goods['final_amount'];
        $arr['coupon_price'] = $coupon_signal_price;
        $arr['discount_signal_price'] = $discount_signal_price;
        $arr['discount_num'] = $discount_num;
        $arr['all_discount_prcie'] = $discount_signal_price+$coupon_signal_price;
        $arr['goods_amount'] = $goods_num*$goods['final_amount'];
        $arr['final_amount'] = $goods['final_amount']*$goods_num-$discount_signal_price*$goods_num-$coupon_signal_price*$goods_num;
        $arr['storeid'] = $store_id;
        $arr['is_online'] = 0;
        $arr['store_goods_stock_id'] = $goods['id'];
        $arr['addtime'] = time();
        $arr['chengben'] = $goods['chengben'];
        $arr['chengben_price'] = $goods['chengben_price'];


//        $arr = [
//            'uid'=>$uid,
//            'spec_id'=>$goods['goods_spec_id'],
//            'spec_detail'=>$goods['title'],
//            'goods_id'=>$goods['goods_id'],
//            'goods_num'=>$goods_num[$k],
//            'spec_price'=>$goods['final_amount'],
//            'coupon_price'=>$coupon_signal_price,
//            'discount_signal_price'=>$discount_signal_price,
//            'all_discount_prcie'=>$discount_signal_price+$coupon_signal_price,
//            'final_amount'=>$goods['final_amount']*$goods_num[$k]-$discount_signal_price*$goods_num[$k]-$coupon_signal_price,
//            'storeid'=>$store_id,
//            'is_online'=>0,
//            'store_goods_stock_id'=>$goods['id'],
//            'addtime'=>time(),
//            'chengben'=>$goods['chengben'],
//            'chengben_price'=>$goods['chengben_price']
//        ];          //订单详情记录

        return $arr;
    }

    /**
     * @Author  lingyun
     * @Desc    创建商品库存记录
     */
    private function create_goods_stock_log($store_id,$goods,$goods_num,$sn){
        //门店库存记录数据
        $store_goods_stock_arr['goods_id'] = $goods['goods_id'];
        $store_goods_stock_arr['goods_spec_id'] = $goods['goods_spec_id'];
        $store_goods_stock_arr['title'] = '';
        $store_goods_stock_arr['store_id'] = $store_id;
        $store_goods_stock_arr['order_id'] = '';
        $store_goods_stock_arr['types'] = 2;
        $store_goods_stock_arr['ruku_num'] = 0;
        $store_goods_stock_arr['tuihuo_num'] = 0;
        $store_goods_stock_arr['chuku_num'] = $goods_num;
        $store_goods_stock_arr['sunhao_num'] = 0;
        $store_goods_stock_arr['remark'] = '售卖'.$goods_num;
        $store_goods_stock_arr['cur_stock'] = $goods['stock'] - $goods_num;
        $store_goods_stock_arr['addtime'] = time();
        $store_goods_stock_arr['order_sn'] = $sn;

        //门店库存记录数据
//            $store_goods_stock_arr[$k]['goods_id'] = $goods['goods_id'];
//            $store_goods_stock_arr[$k]['goods_spec_id'] = $goods['goods_spec_id'];
//            $store_goods_stock_arr[$k]['title'] = '';
//            $store_goods_stock_arr[$k]['store_id'] = $store_id;
//            $store_goods_stock_arr[$k]['order_id'] = '';
//            $store_goods_stock_arr[$k]['types'] = 2;
//            $store_goods_stock_arr[$k]['ruku_num'] = 0;
//            $store_goods_stock_arr[$k]['tuihuo_num'] = 0;
//            $store_goods_stock_arr[$k]['chuku_num'] = $goods_num[$k];
//            $store_goods_stock_arr[$k]['sunhao_num'] = 0;
//            $store_goods_stock_arr[$k]['remark'] = '售卖'.$goods_num[$k];
//            $store_goods_stock_arr[$k]['cur_stock'] = $goods['stock'] - $goods_num[$k];
//            $store_goods_stock_arr[$k]['addtime'] = time();
//            $store_goods_stock_arr[$k]['order_sn'] = $sn;

        return $store_goods_stock_arr;
    }

    /**
     * @Author  lingyun
     * @Desc    获取会员信息
     * 2018-06-08
     */
    private function get_member($mobile,$uid){
        if(empty($mobile)){
            return array();
        }else{
            $member = db('user')->where('mobile',$mobile)->field('uid,user_money,realname,mobile,pay_code,level_id')->find();
            if(!empty($member)){
                if($member['uid'] != $uid){
                    $this->error('请先查询会员信息','');
                }
                return $member;
            }else{
                $member = db('user')->where('pay_code',$mobile)->field('uid,user_money,realname,mobile,pay_code,level_id')->find();
                if(empty($member)){
                    return array();
                }else{
                    if($member['uid'] != $uid){
                        $this->error('请先查询会员信息','');
                    }
                    return $member;
                }
            }
        }
    }

    /**
     * @Author  lingyun
     * @Desc    获取门店信息
     * 2018-06-08
     */
    private function get_store(){
        $store_id = session('cash_user')['store_id'];
        $store = db('store')->where('id',$store_id)->find();

        return $store;
    }

    /**
     * @Author  lingyun
     * @Desc    获取优惠券信息
     * 2018-06-09
     */
    private function get_coupon($coupon_id,$all_num){
        $coupon = db('user_ycard')->where('coupon_id',$coupon_id)->find();
        if(empty($coupon)){
            $coupon_signal_price = 0;
            $coupon['reduce'] = 0;
            $coupon['id'] = 0;
        }else{
            $coupon_signal_price = sprintf("%.2f",substr(sprintf("%.3f", $coupon['reduce']/$all_num), 0, -1));
        }

//        if(!empty($post['coupon_id'])){     //使用优惠券
//            $coupon = db('user_ycard')->where('id',$post['coupon_id'])->find();
//
//            $coupon_signal_price = sprintf("%.2f",substr(sprintf("%.3f", $coupon['reduce']/$all_num), 0, -2));
//        }else{
//            $coupon_signal_price = 0;
//            $coupon['reduce'] = 0;
//        }

        return ['coupon'=>$coupon,'coupon_signal_price'=>$coupon_signal_price];

    }

    private function back(){
        if($pay_type == 1 && $store['is_jiameng'] == 1){            //加盟店
            if($pay_type_two == 0){         //全款支付
                $pay_log_arr = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>$pay_type,
                    'pay_sign'=>1,
                    'amount'=>$final_amount-$discount_amount-$coupon['reduce'],
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$final_amount,
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                //更新商品库存
                foreach($store_goods_stock_arr as $k => $v){
                    db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志


                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$final_amount-$discount_amount-$coupon['reduce'],
                    'cur_credit'=>$store['credit']+$final_amount-$discount_amount-$coupon['reduce'],
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>$pay_type
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $store['total_amount']+$ffinal_amount;
                $store_credit_arr[$fild] = $store[$fild]+$ffinal_amount;

                db('store')->where('id',$store_id)->update($store_credit_arr);
            }else{
                $log_money = $final_amount-$discount_amount-$coupon['reduce']-$pay_type_two;
                $pay_log_arr1 = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>$pay_type,
                    'pay_sign'=>1,
                    'amount'=>$log_money,
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$log_money,
                    'addtime'=>time()
                ];
                $pay_log_arr2 = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>3,
                    'pay_sign'=>1,
                    'amount'=>-$pay_type_two,
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$pay_type_two,
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr1);            //新增支付记录
                db('pay_log')->insert($pay_log_arr2);            //新增支付记录

                $data_wallet_arr = [
                    'uid'=>$uid,
                    'admin_id'=>0,
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'pay_time'=>time(),
                    'pay_status'=>1,
                    'pay_type'=>3,
                    'amount'=>$pay_type_two,
                    'cur_amount'=>$member['user_money']-$pay_type_two,
                    'sign'=>2,
                    'chargetype'=>1,
                    'charge_cn'=>'支付订单',
                    'addtime'=>time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                db('user')->where('uid',$uid)->setDec('user_money',$pay_type_two);

                db('store')->where('id',$store_id)->setInc('user_money',$pay_type_two);     //更新门店会员卡金额数量
                //更新商品库存
                foreach($store_goods_stock_arr as $k => $v){
                    db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志

                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$log_money,
                    'cur_credit'=>$store['total_amount']+$log_money,
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>$pay_log_arr1['pay_type']
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $log_money;
                $store_credit_arr[$fild] = $store[$fild]+$log_money;
                db('store')->where('id',$store_id)->update($store_credit_arr);

                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$pay_type_two,
                    'cur_credit'=>$store['total_amount']+$log_money+$pay_type_two,
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>3
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $log_money;
                $store_credit_arr['credit'] = $store['credit']+$log_money+$pay_type_two;
                db('store')->where('id',$store_id)->update($store_credit_arr);
            }
        }

        if($pay_type == 2 && $store['is_jiameng'] == 1){            //加盟店
            if($pay_type_two == 0){         //全款支付
                $pay_log_arr = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>$pay_type,
                    'pay_sign'=>1,
                    'amount'=>$final_amount-$discount_amount-$coupon['reduce'],
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$final_amount,
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr);            //新增支付记录

                //更新商品库存
                foreach($store_goods_stock_arr as $k => $v){
                    db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志


                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$final_amount-$discount_amount-$coupon['reduce'],
                    'cur_credit'=>$store['total_amount']+$final_amount-$discount_amount-$coupon['reduce'],
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>$pay_type
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $store['total_amount']+$ffinal_amount;
                $store_credit_arr[$fild] = $store[$fild]+$ffinal_amount;

                db('store')->where('id',$store_id)->update($store_credit_arr);
            }else{
                $log_money = $final_amount-$discount_amount-$coupon['reduce']-$pay_type_two;
                $pay_log_arr1 = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>$pay_type,
                    'pay_sign'=>1,
                    'amount'=>$log_money,
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$log_money,
                    'addtime'=>time()
                ];
                $pay_log_arr2 = [
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'order_type'=>2,
                    'uid'=>$uid,
                    'store_id'=>$store_id,          //门店id
                    'pay_type'=>3,
                    'pay_sign'=>1,
                    'amount'=>-$pay_type_two,
                    'remark'=>'线下购买商品，订单号'.$sn.'，总价：'.$pay_type_two,
                    'addtime'=>time()
                ];
                db('pay_log')->insert($pay_log_arr1);            //新增支付记录
                db('pay_log')->insert($pay_log_arr2);            //新增支付记录

                $data_wallet_arr = [
                    'uid'=>$uid,
                    'admin_id'=>0,
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'order_sn'=>$sn,
                    'pay_time'=>time(),
                    'pay_status'=>1,
                    'pay_type'=>3,
                    'amount'=>$pay_type_two,
                    'cur_amount'=>$member['user_money']-$pay_type_two,
                    'sign'=>2,
                    'chargetype'=>1,
                    'charge_cn'=>'支付订单',
                    'addtime'=>time()
                ];
                //记录余额记录
                db('user_wallet_log')->data($data_wallet_arr)->insert();       //记录余额记录
                db('user')->where('uid',$uid)->setDec('user_money',$pay_type_two);

                db('store')->where('id',$store_id)->setInc('user_money',$pay_type_two);     //更新门店会员卡金额数量
                //更新商品库存
                foreach($store_goods_stock_arr as $k => $v){
                    db('store_goods_stock')->where(['goods_id'=>$v['goods_id'],'goods_spec_id'=>$v['goods_spec_id'],'store_id'=>$v['store_id'],'is_deleted'=>0])->setDec('stock',$v['chuku_num']);
                    $store_goods_stock_arr[$k]['order_id'] = $order_id;
                }
                db('store_goods_log')->insertAll($store_goods_stock_arr);       //更新商品库存变更日志

                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$log_money,
                    'cur_credit'=>$store['total_amount']+$log_money,
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>$pay_log_arr1['pay_type']
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $log_money;
                $store_credit_arr[$fild] = $store[$fild]+$log_money;
                db('store')->where('id',$store_id)->update($store_credit_arr);

                $store_credit_log = [
                    'store_id'=>$store_id,
                    'order_id'=>$order_id,
                    'type'=>1,
                    'credit'=>$pay_type_two,
                    'cur_credit'=>$store['total_amount']+$log_money+$pay_type_two,
                    'remark'=>'销售商品收入',
                    'addtime'=>time(),
                    'order_type'=>1,
                    'order_sn'=>$sn,
                    'pay_type'=>3
                ];
                db('store_credit_log')->insert($store_credit_log);
                $store_credit_arr['total_amount'] = $log_money;
                $store_credit_arr['credit'] = $store['credit']+$log_money+$pay_type_two;
                db('store')->where('id',$store_id)->update($store_credit_arr);
            }
        }
    }


}